package com.huatai.user.service.impl;

import com.huatai.common.config.MinioAPI;
import com.huatai.common.error.exception.ServiceException;
import com.huatai.common.util.DateTimeUtil;
import com.huatai.user.vo.UploadlogoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.huatai.user.constant.MinioBucket;

import java.io.InputStream;
import java.time.LocalDate;

/**
 * @author zsj
 */
@Service
@Slf4j
public class LogoFileService {


	@Autowired
	private MinioAPI minioAPI;

	private final static String SLASH = "/";

	private final static String FILE_NAME_PREFIX_SEPARATOR = "-";

	@Value("${minio.PREURL}")
	private String minioUrl;

	/**
	 * logo上传
	 */
	public UploadlogoVo upload(MultipartFile file) {
		try (InputStream is = file.getInputStream()) {
			String bucketName = MinioBucket.GH_MODEL_BUCKET_NAME_PRIVATE;
			String objectKey = getObjectKey(file.getSize(), file.getOriginalFilename());
			minioAPI.uploadInputStream(bucketName, objectKey, is, file.getContentType());
			return	new UploadlogoVo(minioUrl + "/" + MinioBucket.GH_MODEL_BUCKET_NAME_PRIVATE + "/" + objectKey,objectKey);
		} catch (Exception e) {
			log.error("上传失败，", e);
			throw new ServiceException("上传失败，请重新上传");
		}
	}
	/**
	 * 获取存储路径
	 * @param fileSize
	 * @param fileName
	 * @return
	 */
	private String getObjectKey(Long fileSize,String fileName) {
		String date = DateTimeUtil.format(LocalDate.now(),"yyyyMMdd");

		StringBuilder objectKey = new StringBuilder(date);
		objectKey.append(SLASH).append(fileSize).append(FILE_NAME_PREFIX_SEPARATOR).append(fileName);
		return objectKey.toString();
	}

}
